﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

using Eforcity.Common35;
using Eforcity.Data.Common35;

namespace Eforcity.EbayApi
{
    public class EbayBMApiUtility
    {
        public static string GetApiResponse(string requestXml, string callName, string authToken, string endpoint, int timeoutSecond)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            int dataLen = encoding.GetByteCount(requestXml);
            byte[] utf8Bytes = Encoding.UTF8.GetBytes(requestXml);

            //Setup The Request (inc. HTTP Headers)
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.ContentLength = utf8Bytes.Length;
            request.Headers.Add("X-EBAY-SOA-OPERATION-NAME: " + callName);
            request.Headers.Add("X-EBAY-SOA-SECURITY-TOKEN: " + authToken);
            request.Timeout = timeoutSecond * 1000;

            //Send The Request
            try
            {
                StreamWriter sw = new StreamWriter(request.GetRequestStream());
                sw.Write(requestXml);
                sw.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string responseXml = sr.ReadToEnd();

                return responseXml;
            }
            catch (WebException ex)
            {
                //Error has occured whilst requesting
                throw ex;
            }
        }

        public static TimeSpan GetEbayDuration(string durationStr)
        {
            string durationPattern = @"P(?<days>\d+)DT(?<hours>\d+)H(?<minutes>\d+)M(?<seconds>\d+)S";
            Regex durationRgx = new Regex(durationPattern, RegexOptions.IgnoreCase);
            Match match = durationRgx.Match(durationStr);
            if (match.Success)
            {
                int days = ConvertUtility.ToInt(match.Groups["days"].Value, -1);
                int hours = ConvertUtility.ToInt(match.Groups["hours"].Value, -1);
                int minutes = ConvertUtility.ToInt(match.Groups["minutes"].Value, -1);
                int seconds = ConvertUtility.ToInt(match.Groups["seconds"].Value, -1);

                TimeSpan duration = new TimeSpan(days, hours, minutes, seconds);

                return duration;
            }
            else
            {
                throw new Exception("Duration string is not matched the format.");
            }
        }
    }
}
